# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10059': {
        # 全速支付  alipay-H5 30-3000 3.1% DWC
        # 全速支付  wechat-H5 30-3000 3.8% DWC
        'API_KEY': '6fae372852964d8b8ed06aa7dad7f7e9 ',
        'gateway': 'https://api.gzname.com:8888/lpay/pay/gateway',
    },
    '10082': {
        # 全速支付  alipay-H5 30-3000 3.0% DWC
        # 全速支付  wechat-H5 30-3000 3.5% DWC
        # 全速支付  快捷 30-3000 1.3% DWC
        'API_KEY': 'ae51484dc7964aa9b8c67f4bc36dbce0 ',
        'gateway': 'https://api.gzname.com:8888/lpay/pay/gateway',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _gen_sign(s):
    if isinstance(s, str):
        input_string = s.decode('ascii', 'ignore').encode('ascii')
    m = hashlib.md5()
    m.update(input_string.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(d, key):
    s = '{}{}{}{}'.format(d['out_trade_no'], d['total_fee'],
                          d['mch_id'], key)
    return _gen_sign(s)


def generate_notify_sign(d, app_id, key):
    s = '{}{}{}{}{}'.format(
        d['out_trade_no'], d['transaction_id'],
        d['time_end'], app_id, key)
    return _gen_sign(s)


def verify_notify_sign(params, app_id, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, app_id, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("quansupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    # 11:支付宝WAP支付; 17:支付宝个人转账WAP支付; 21:微信WAP支付; 31:QQ钱包WAP支付; 41:银联快捷支付; 42:银行卡网关支付; 51:京东H5支付。
    if service == 'alipay':
        return '11'
    elif service == 'wechat':
        return '21'
    elif service == 'unionpay':
        return '41'
    return '11'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='get'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mch_id', app_id),
        ('out_trade_no', str(pay.id)),
        ('total_fee', str(int(pay_amount * 100))),
        ('pay_type', _get_pay_type(service)),
        ('is_raw', int(1)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("quansupay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['out_trade_no'])
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("quansupay notify data: %s, order_id is: %s", data, data['out_trade_no'])
    verify_notify_sign(data, app_id, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('quansupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])
    trade_no = data['transaction_id']
    total_fee = float(data['total_fee']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 0 and total_fee > 0.0:
        _LOGGER.info('quansupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass
